package com.ruoyi.controller;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.entity.ActReDeployment;
import com.ruoyi.service.*;
import com.ruoyi.vo.FlowSaveXmlVO;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.converter.BpmnXMLConverter;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 工作流程定义
 * </p>
 *
 * @author XuanXuan
 *
 */
@Slf4j
@RestController("流程定义")
@RequestMapping("/flowable/definition")
public class FlowDefinitionController {

    @Autowired
    private FlowDefinitionServiceImpl flowDefinitionService;

    @Autowired
    private SysFormServiceImpl sysFormService;

    @Autowired
    private SysDeployFormServiceImpl sysDeployFormService;


    @Autowired
    private FlowTaskServiceImpl flowTaskService;

    @Resource
    protected RuntimeService runtimeService;

    @Resource
    protected HistoryService historyService;

    @Autowired
    private SysUserServiceImpl userService;

    @Resource
    private SysRoleServiceImpl sysRoleService;


    @GetMapping(value = "/list")

    public AjaxResult list(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(required = false) String name) {
        return AjaxResult.success(flowDefinitionService.list(name, pageNum, pageSize));
    }


    @GetMapping(value = "/getDataFormFlowList")
    public AjaxResult getDataFormFlowList(String name) {
        return AjaxResult.success(flowDefinitionService.getDataFormFlowList(name));
    }

    @RequestMapping("/getByDeploymentId")
    public Object getByDeploymentId(String deploymentId) throws IOException {
        return flowDefinitionService.getByDeploymentId(deploymentId);
    }

    /**
     * 生成流程图
     *
     * @param processId 任务ID
     * @return
     */
    @RequestMapping("/readProcessXml/{processId}")
    public AjaxResult readProcessXml(@PathVariable("processId") String processId) throws UnsupportedEncodingException {
        String processDefinitionId;
        // 获取当前的流程实例
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        // 如果流程已经结束，则得到结束节点
        if (Objects.isNull(processInstance)) {
            HistoricProcessInstance pi = historyService.createHistoricProcessInstanceQuery().processInstanceId(processId).singleResult();
            processDefinitionId = pi.getProcessDefinitionId();
        } else {// 如果流程没有结束，则取当前活动节点
            // 根据流程实例ID获得当前处于活动状态的ActivityId合集
            ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
            processDefinitionId = pi.getProcessDefinitionId();
        }
        BpmnModel bpmnModel = SpringUtils.getBean(RepositoryService.class).getBpmnModel(processDefinitionId);
        BpmnXMLConverter bpmnConverter = new BpmnXMLConverter();
        String xml = new String(bpmnConverter.convertToXML(bpmnModel), "UTF-8");
        return AjaxResult.success("", xml);
    }


    @GetMapping("/readXml/{deployId}")
    public AjaxResult readXml(@PathVariable(value = "deployId") String deployId) {
        try {
            return flowDefinitionService.readXml(deployId);
        } catch (Exception e) {
            return AjaxResult.error("加载xml文件异常");
        }

    }


    @GetMapping("/readXmlByKey/{key}")
    public AjaxResult readXmlByKey(@PathVariable(value = "key") String key) {
        try {
            return flowDefinitionService.readXmlByKey(key);
        } catch (Exception e) {
            return AjaxResult.error("加载xml文件异常");
        }
    }


    @GetMapping("/readImage/{deployId}")
    public void readImage(@PathVariable(value = "deployId") String deployId, HttpServletResponse response) {
        OutputStream os = null;
        BufferedImage image = null;
        try {
            image = ImageIO.read(flowDefinitionService.readImage(deployId));
            response.setContentType("image/png");
            os = response.getOutputStream();
            if (image != null) {
                ImageIO.write(image, "png", os);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.flush();
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    @PostMapping(value = "/createDeployment")
    public Object createDeployment(@RequestBody ActReDeployment vo) {
        flowDefinitionService.createDeployment(vo);
        return "";
    }

    @PostMapping(value = "/updateUseDeployment")
    public Object updateUseDeployment(@RequestBody ActReDeployment vo) {
        flowDefinitionService.updateUseDeployment(vo);
        return "";
    }

    @PostMapping(value = "/deleteDeployment")
    public Object deleteDeployment(@RequestBody ActReDeployment vo) {
        flowDefinitionService.deleteDeployment(vo);
        return "";
    }

    @PostMapping("/save")
    public AjaxResult save(@RequestBody FlowSaveXmlVO vo) {
        if (StrUtil.isBlank(vo.getXml())) {
            return AjaxResult.success("导入成功");
        }
        InputStream in = null;
        try {
            in = new ByteArrayInputStream(vo.getXml().getBytes(StandardCharsets.UTF_8));
            flowDefinitionService.importFile(vo, in);
        } catch (Exception e) {
            log.error("导入失败:", e);
            return AjaxResult.success(e.getMessage());
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                log.error("关闭输入流出错", e);
            }
        }

        return AjaxResult.success("导入成功");
    }


    @PostMapping("/start/{procDefId}")
    public AjaxResult start(@PathVariable(value = "procDefId") String procDefId,
                            @RequestBody Map<String, Object> variables) {
        return flowDefinitionService.startProcessInstanceById(procDefId, variables);

    }

    @GetMapping(value = "/getCanAssignTaskList")
    public AjaxResult getCanAssignTaskList(String procInsId) {
        List<Map<String, Object>> list = flowDefinitionService.getCanAssignTaskList(procInsId);
        return AjaxResult.success(list);
    }


    @PutMapping(value = "/updateState")
    public AjaxResult updateState(@RequestParam Integer state,
                                  @RequestParam String deployId) {
        flowDefinitionService.updateState(state, deployId);
        return AjaxResult.success();
    }


    @DeleteMapping(value = "/{deployIds}")
    public AjaxResult delete(@PathVariable String[] deployIds) {
        for (String deployId : deployIds) {
            flowDefinitionService.delete(deployId);
        }
        return AjaxResult.success();
    }

    @RequestMapping(value = "/delDeploymentForm")
    public AjaxResult delDeploymentForm(String formId) {
        flowDefinitionService.delDeploymentForm(formId);
        return AjaxResult.success();
    }


    @GetMapping("/userList")
    public AjaxResult userList(SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        return AjaxResult.success(list);
    }


    @GetMapping("/roleList")
    public AjaxResult roleList(SysRole role) {
        List<SysRole> list = sysRoleService.selectRoleList(role);
        return AjaxResult.success(list);
    }

}